package com.futu.intelligence.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class AMapUtil {

    @Value("${amap.key}")
    private String key;

    @Value("${amap.search-url}")
    private String searchUrl;

    @Value("${amap.route-url}")
    private String routeUrl;

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 搜索景点
    public String searchAttraction(String keyword, String city) {
        try {
            String url = String.format("%s?key=%s&keywords=%s&region=%s&city_limit=true",
                searchUrl, key, keyword, city);

            return httpGet(url);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 规划路线
    public String planRoute(String origin, String destination) {
        try {
            String url = String.format("%s?key=%s&origin=%s&destination=%s",
                routeUrl, key, origin, destination);

            return httpGet(url);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // HTTP GET请求
    private String httpGet(String url) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                return EntityUtils.toString(response.getEntity());
            }
        }
    }

    // 解析地点坐标
    public Map<String, Double> parseLocation(String jsonResponse) {
        try {
            JsonNode root = objectMapper.readTree(jsonResponse);
            JsonNode pois = root.path("pois");

            if (pois.isArray() && pois.size() > 0) {
                String location = pois.get(0).path("location").asText();
                String[] coordinates = location.split(",");

                Map<String, Double> result = new HashMap<>();
                result.put("longitude", Double.parseDouble(coordinates[0]));
                result.put("latitude", Double.parseDouble(coordinates[1]));

                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
